﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Security;
using OpenRasta.Web;
using umbraco.cms.businesslogic.member;
using uREST.Core.Extensions;

namespace uREST.CMS.Extensions
{
    public static class MemberExtensions
    {
        public static Resources.Member ToResource(this Member member)
        {
            var resource = new Resources.Member
            {
                Id = member.Id,
                Href = typeof(Resources.Member).CreateUri("Member", new { id = member.Id }).ToString(),
                DisplayName = member.Text,
                Username = member.LoginName,
                Token = member.Tokenize(),
                Email = member.Email,
                MemberTypeAlias = member.ContentType.Alias,
                Roles = new List<string>(Roles.GetRolesForUser(member.LoginName))
            };

            foreach (var property in member.GenericProperties)
            {
                resource.Properties.Add(new Resources.Property
                {
                    Key = property.PropertyType.Alias,
                    Value = property.Value == System.DBNull.Value ? null : property.Value
                });
            }

            return resource;
        }

        public static List<Resources.Member> ToResourceList(this Member[] memberList)
        {
            return new List<Member>(memberList).ToResourceList();
        }

        public static List<Resources.Member> ToResourceList(this List<Member> memberList)
        {
            var resourceList = new List<Resources.Member>();
            resourceList.AddRange(memberList.Select(member => member.ToResource()));
            return resourceList;
        }
    }
}
